package com.zhao.controller.admin;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhao.Util.FileSize;
import com.zhao.Util.MD5_Shiro;
import com.zhao.comm.log.MyLog;
import com.zhao.pojo.*;
import com.zhao.pojo.comm.UserInfo;
import com.zhao.service.*;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;


@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;
    @Autowired
    RoleService roleService;
    @Autowired
    MenuService menuService;
    @Autowired
    WalletService walletService;
    @Autowired
    ArticleService articleService;
    @Autowired
    DatafileService datafileService;
    //admin后台首页
    @RequestMapping("/index")
    public String index(Model model){
      /*  model.addAttribute("a","/article/add_article");*/
        User loginUser = (User) SecurityUtils.getSubject().getPrincipal();
        QueryWrapper<Menu> wrapper=new QueryWrapper<>();
        wrapper.eq("father","0");
        wrapper.orderByAsc("idx");
        List<Menu> menus = menuService.list(wrapper);
        for (Menu menu: menus) {
            QueryWrapper<Menu> wrapper1=new QueryWrapper<>();
            wrapper1.eq("father",menu.getMenuId());
            menu.setChildren(menuService.list(wrapper1));
        }
        Wallet wallet = walletService.getOne(new QueryWrapper<Wallet>().eq("uid", loginUser.getUserId()));
        model.addAttribute("wallet",wallet);
        model.addAttribute("user",loginUser);
        model.addAttribute("menus",menus);
        return "admin/index";
    }
    /*用户管理*/
    @RequestMapping("/data_user")
    public String queryUser(@RequestParam(value = "pageNum",defaultValue = "1")Integer pageNum,
                            @RequestParam(value = "size",required = false,defaultValue = "5")Integer size,
                            @RequestParam(value = "username",required = false)String username,
                            Model model) {
        QueryWrapper<User> wrapper=new QueryWrapper<>();
        if (username!=null&&!"".equals(username)){
            wrapper.like("username",username);
        }
        Page<User> page = new Page<>(pageNum, size);
        userService.page(page,wrapper);
        model.addAttribute("users",page);
        return "admin/data_user";
    }
    /*添加页面跳转*/
    @RequestMapping("/addUser")
    public String addUser(Model model){
        List<Role> roles = roleService.list(null);
        model.addAttribute("roles",roles);
        return "admin/add_user";
    }
    /*删除用户*/
    //@MyLog(value = "删除用户")
    @GetMapping("/delUser/{id}")
    public String delUser(@PathVariable("id")Integer id){
        userService.delUser(id);
        return "redirect:/user/data_user";
    }
    /*查询一个跳修改页面*/
    @GetMapping("/editUser/{id}")
    public String editUser(@PathVariable("id")Integer id,Model model){
        System.out.println(id);
        QueryWrapper<User> wrapper=new QueryWrapper<>();
        wrapper.eq("user_id",id);
        User user = userService.getOne(wrapper);
        List<Role> roles = roleService.list(null);
        model.addAttribute("roles",roles);
        model.addAttribute("user",user);
        List<String> list = userService.checked(id);
        model.addAttribute("checked",list);
        return "admin/update_user";
    }
    //@MyLog(value = "修改用户信息")
    @ResponseBody
    @RequestMapping("/updateUser")
    public String updateUser(User user){
        System.out.println("---------------------------------------------------------------");
        //user 的密码需要加密
        userService.saveOrUpdateUser(user);
        return "1";
    }
    //个人中心->基本信息 显示
    @RequestMapping("/updateUserOne")
    public String updateUserOne(Model model) {
        User loginUser = (User) SecurityUtils.getSubject().getPrincipal();
        User user = userService.getById(loginUser.getUserId());
        Wallet wallet = walletService.getOne(new QueryWrapper<Wallet>().eq("uid", user.getUserId()));
        String userRoleName = roleService.getUserRoleName(user.getUserId());
        user.setRname(userRoleName);
        model.addAttribute("wallet",wallet);
        model.addAttribute("user",user);
        return "admin/update_user_one";
    }
    //个人信息->基本信息修改
    @ResponseBody
    @RequestMapping("/updateUserBase")
    public String updateUserBase(UserInfo userInfo) {
        String res="1";
        System.out.println(userInfo.toString());
        User user = userService.getById(userInfo.getUserId());
        //修改笔名
        if (!userInfo.getUserAccount().equals(user.getUserAccount())){
            User user_account = userService.getOne(new QueryWrapper<User>().eq("user_account", userInfo.getUserAccount()));
            if (user_account==null){
                user.setUserAccount(userInfo.getUserAccount());
                userService.updateById(user);
                List<Article> articleList = articleService.list(new QueryWrapper<Article>().eq("author", userInfo.getUserAccount()));
                for (Article article : articleList) {
                    article.setAuthor(userInfo.getUserAccount());
                }
                articleService.updateBatchById(articleList);
                List<Datafile> datafileList = datafileService.list(new QueryWrapper<Datafile>().eq("author", userInfo.getUserAccount()));
                for (Datafile datafile : datafileList) {
                    datafile.setAuthor(userInfo.getUserAccount());
                }
                datafileService.updateBatchById(datafileList);
            }else {
                res="2";//笔名已存在
            }
        }
        //wallet
        Wallet wallet = walletService.getOne(new QueryWrapper<Wallet>().eq("uid", userInfo.getUserId()));
        wallet.setProvince(userInfo.getProvince());
        wallet.setCity(userInfo.getCity());
        wallet.setArea(userInfo.getArea());
        wallet.setBirthday(userInfo.getBirthday());
        wallet.setSex(userInfo.getSex());
        wallet.setUserinfo(userInfo.getUserinfo());
        walletService.updateById(wallet);
        return res;
    }
    //修改头像弹出页
    @RequestMapping("/updateUserImg")
    public String updateUserImg(){
        return "admin/updateUserImg";
    }
    @ResponseBody
    @RequestMapping("/userUploadImg")
    public String userUploadImg(MultipartFile file) throws IOException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSS");
        String res = sdf.format(new Date());

        // uploads文件夹位置
        //String rootPath = request.getSession().getServletContext().getRealPath("resource/uploads/");
        String rootPath =System.getProperty("user.dir")+"/upload/userimg/";
        //获取文件大小
        String size = FileSize.FormetFileSize(file.getSize());
        // 原始名称
        String originalFileName = file.getOriginalFilename();
        // 新文件名
        String newFileName = "sliver" + res + originalFileName.substring(originalFileName.lastIndexOf("."));
        // 创建年月文件夹
        Calendar date = Calendar.getInstance();
        File dateDirs = new File(date.get(Calendar.YEAR) + File.separator + (date.get(Calendar.MONTH)+1));

        // 新文件
        File newFile = new File(rootPath + File.separator + dateDirs + File.separator + newFileName);
        // 判断目标文件所在目录是否存在
        if( !newFile.getParentFile().exists()) {
            // 如果目标文件所在的目录不存在，则创建父目录
            newFile.getParentFile().mkdirs();
        }
        System.out.println(newFile);
        // 将内存中的数据写入磁盘
        file.transferTo(newFile);
        // 完整的url
        String fileUrl = date.get(Calendar.YEAR) + "/" + (date.get(Calendar.MONTH)+1) + "/" + newFileName;
        User loginUser = (User) SecurityUtils.getSubject().getPrincipal();
        Wallet wallet = walletService.getOne(new QueryWrapper<Wallet>().eq("uid", loginUser.getUserId()));
        if (wallet.getAvatar()!=null){
            System.out.println("2021/8/moren.png================================================>"+wallet.getAvatar());
            if (!wallet.getAvatar().equals("2021/8/moren.png")){
                File file1 = new File(rootPath+wallet.getAvatar());
                if (file1.exists()) {
                    file1.delete();
                    System.out.println("文件已经被成功删除");
                }
            }
        }
        wallet.setAvatar(fileUrl);
        walletService.updateById(wallet);
        return "1";
    }
    @RequestMapping("/updateUserInfo")
    public String updateUserInfo(Model model){
        User loginUser = (User) SecurityUtils.getSubject().getPrincipal();
        User user = userService.getById(loginUser.getUserId());
        int i=0;
        if (user.getUserIphone()!=null&&!user.getUserIphone().equals("")){
            i+=30;
        }
        if (user.getUserEmail()!=null&&!user.getUserEmail().equals("")){
            i+=30;
        }
        List<User> user_pass = userService.list(new QueryWrapper<User>().eq("user_pass", user.getUserPass()));
        if (user_pass!=null){
            if(user_pass.size()<3){
                i+=30;
            }else if(user_pass.size()<10){
                i+=15;
            }else {
                model.addAttribute("code","存在风险，请修改密码");
            }
        }
        model.addAttribute("i",i);
        model.addAttribute("user",user);
        return "admin/update_user_info";
    }
    @RequestMapping("/editUserInfo/{res}")
    public String editUSerInfo(@PathVariable String res, Model model){
        User loginUser = (User) SecurityUtils.getSubject().getPrincipal();
        User user = userService.getById(loginUser.getUserId());
        model.addAttribute("user",user);
        model.addAttribute("res",res);
        return "admin/updateUserInfo";
    }
    //验证原密码
    @ResponseBody
    @RequestMapping("/oldPassCheck")
    public String oldPassCheck(String username,String password){
        byte[] decoded = Base64.getDecoder().decode(password);
        String pass = new String(decoded);
        User user = userService.getOne(new QueryWrapper<User>().eq("user_name", username));
        String newPwd = MD5_Shiro.encryptPassword("MD5",pass,user.getSalt(),1024);
        if (user.getUserPass().equals(newPwd)){
            return "1";//相等
        }else {
            return "0";//否
        }
    }
    //修改 user信息
    @ResponseBody
    @RequestMapping("/updateUserInfoAll")
    public String updateUserInfoAll(String res,@RequestParam(value = "value",required = false)String value){
        User loginUser = (User) SecurityUtils.getSubject().getPrincipal();
        User user = userService.getById(loginUser.getUserId());
        String code=userService.updateUserInfoAll(user,res,value);
        return code;
    }
}
